<template>
  <div class="single-page">
    <div class="main-content">
      <div class="table-bar" @keyup.enter="searchHandleFunc">
        <div class="search-layout">
          <div class="search-item">
            <div class="search-label_80">姓名：</div>
            <a-input
                v-model:value="paramData.name"
                placeholder="请输入姓名"
                allow-clear
            />
          </div>
          <div class="search-item">
            <div class="search-label_80 margin-left_20">手机号：</div>
            <a-input
                allow-clear
                v-model:value="paramData.phone"
                placeholder="请输入手机号"
            />
          </div>
          <a-button
              type="primary"
              class="margin-left_50"
              @click="searchHandleFunc"
          >
            <template #icon>
              <SearchOutlined/>
            </template>
            查询
          </a-button>
        </div>
        <div class="search-layout">
          <div class="search-btn">
            <div>
              <a-button
                  v-track="'点击用户列表创建用户'"
                  type="primary"
                  class="margin-left_20"
                  @click="addHandleFunc"
              >
                <template #icon>
                  <PlusOutlined/>
                </template>
                创建用户
              </a-button
              >
            </div>
          </div>
        </div>
      </div>
      <div class="table-style">
        <a-table
            :columns="columns"
            :data-source="dataSource"
            bordered
            size="middle"
            :pagination="pagination"
            :rowKey="(record:any) => record.id"
            :loading="state.loading"
            @change="handleTableChange"
            @resizeColumn="handleResizeColumn"
            class="adjust-table"
        >
          <template #bodyCell="{ column, text, record }">
            <template v-if="column.dataIndex === 'roles'">
              <span>
                <a-tag
                    style="margin-top: 5px;"
                    v-for="(role, index) in record.roles"
                    :key="index"
                    :color="role.color"
                >
                  {{ role.label }}
                </a-tag>
              </span>
            </template>

            <template v-if="column.dataIndex === 'status'">
              <span>
                <a-tag
                    :color="record.status == 1 ? 'green' : 'red'"
                >
                  {{ record.status == 1 ? "已启用" : "已禁用" }}
                </a-tag>
              </span>
            </template>

            <template v-if="column.dataIndex === 'operations'">
              <div class="operations-style">
                <div>
                  <a-typography-link @click="updateUserInfo(record)" v-track="'用户列表 编辑'"
                  >编辑
                  </a-typography-link
                  >
                </div>
                <div>
                  <a-popconfirm
                      :title="record.status == 0 ? '是否启用' : '是否禁用'"
                      @confirm="deleteRole(record)"
                      v-track="'用户列表 禁用'"
                      :getPopupContainer="(triggerNode:any) => {return triggerNode.parentNode}"
                  >
                    <a>{{ record.status == 0 ? "启用" : "禁用" }}</a>
                  </a-popconfirm>
                </div>
              </div>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <!-- 添加用户 -->
    <a-modal
        class="addUserModal"
        v-model:visible="modalVisible"
        title="创建用户"
        :confirm-loading="modalConfirmLoading"
        @ok="modalHandleOk"
    >
      <div class="addRole-contain">
        <div>
          <div class="addRole-contain_label">
            <span class="font-color_red">*</span>账号
          </div>
          <a-input v-model:value="addAccountName" allow-clear/>
        </div>
        <div class="margin-top_20">
          <div class="addRole-contain_label">
            <span class="font-color_red">*</span>姓名
          </div>
          <a-input v-model:value="addNameValue" allow-clear/>
        </div>
        <div class="margin-top_20">
          <div class="addRole-contain_label">
            <span class="font-color_red">*</span>手机号
          </div>
          <a-input v-model:value="addPhoneValue" allow-clear/>
        </div>
        <div class="margin-top_20">
          <div class="addRole-contain_label">
            <span class="font-color_red">*</span>角色
          </div>
          <a-select
              placeholder="请选择"
              v-model:value="addRoleValue"
              class="addRole-contain"
              mode="multiple"
          >
            <a-select-option
                v-for="option in selectDataSource"
                :key="option.id"
                :value="option.id"
            >{{ option.name }}
            </a-select-option>
          </a-select>
        </div>
        <div class="margin-top_20">
          <div class="addRole-contain_label">
            <span class="font-color_red">*</span>邮箱
          </div>
          <a-input v-model:value="addEmailValue" allow-clear/>
        </div>
        <div class="margin-top_20">
          <div class="addRole-contain_label">
            <span class="font-color_red">*</span>密码
          </div>
          <a-input-password v-model:value="addPasswordValue" allow-clear/>
        </div>
      </div>
    </a-modal>

    <!-- 更新用户 -->
    <a-modal
        class="addUserModal"
        v-model:visible="updateModalVisible"
        title="更新用户"
        :confirm-loading="updateModalConfirmLoading"
        @ok="updateModalHandleOk"
    >
      <div class="addRole-contain">
        <div>
          <div class="addRole-contain_label">
            <span class="font-color_red">*</span>账号
          </div>
          <a-input v-model:value="updateAccountName" allow-clear/>
        </div>
        <div class="margin-top_20">
          <div class="addRole-contain_label">
            <span class="font-color_red">*</span>姓名
          </div>
          <a-input v-model:value="updateNameValue" allow-clear/>
        </div>
        <div class="margin-top_20">
          <div class="addRole-contain_label">
            <span class="font-color_red">*</span>手机号
          </div>
          <a-input v-model:value="updatePhoneValue" allow-clear/>
        </div>
        <div class="margin-top_20">
          <div class="addRole-contain_label">
            <span class="font-color_red">*</span>角色
          </div>
          <a-select
              placeholder="请选择"
              v-model:value="updateRoleValue"
              class="addRole-contain"
              mode="multiple"
          >
            <a-select-option
                v-for="option in selectDataSource"
                :value="option.id"
            >{{ option.name }}
            </a-select-option
            >
          </a-select>
        </div>
        <div class="margin-top_20">
          <div class="addRole-contain_label">
            <span class="font-color_red">*</span>邮箱
          </div>
          <a-input v-model:value="updateEmailValue" allow-clear/>
        </div>
      </div>
    </a-modal>

    <!-- 创建角色 -->
    <a-modal
        v-model:visible="addRoleVisible"
        title="创建角色"
        :confirm-loading="addRoleLoading"
        @ok="addRoleHandleOk"
        width="400px"
    >
      <div>
        <LabelInput
            labelName="角色名称"
            :inputValue="addRoleName"
            :inputWidth="240"
            @inputChangeFunc="addRoleNameInput"
        >
          <div class="font-color_red">*</div>
        </LabelInput>
      </div>
      <div class="margin-top_20">
        <LabelTextarea
            labelName="角色描述"
            :inputValue="addRoleMark"
            :inputWidth="240"
            @inputChangeFunc="addRoleMarkInput"
        >
          <div class="font-color_red">*</div>
        </LabelTextarea>
      </div>
      <div style="display: flex">
        <div><span class="font-color_red">*</span><span>角色权限</span></div>
        <!-- 角色权限列表 -->
        <a-tree
            v-model:selectedKeys="selectedKeys"
            v-model:checkedKeys="checkedKeys"
            checkable
            :tree-data="selectTreeData"
        >
          <template #title="{ title, key, level }">
            {{ title }}
            <span style="font-size: 12px; color: #1890ff">{{ level }}</span>
          </template>
        </a-tree>
      </div>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import {cloneDeep, template, update} from "lodash-es";
import {
  defineComponent,
  reactive,
  ref,
  onMounted,
  computed,
  inject,
} from "vue";
import type {UnwrapRef} from "vue";
import type {Dayjs} from "dayjs";
import type {TableColumnsType} from "ant-design-vue";
import {message} from "ant-design-vue";
import dayjs from "dayjs";
import {post, apipost, get, mockGet} from "@/service/request";
import type {TableProps} from "ant-design-vue";
import {PlusOutlined, SearchOutlined} from "@ant-design/icons-vue";
import LableIuput from "@/components/formItem/label-input.vue";
import {userInfo} from "@/store/user";
import type {TreeSelectProps} from "ant-design-vue";
import {TreeSelect} from "ant-design-vue";

const userStore = userInfo();
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
const reload: any = inject("reload");

const state = reactive({
  loading: false,
});


const pagination = reactive({
  size: "small",
  showSizeChanger: true,
  position: ["bottomCenter"],
  hideOnSinglePage: true,
  current: 1,
  pageSize: 10,
  total: 0,
  onShowSizeChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize
  },
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize
  },
});

const selectRoles = ref<string[]>([]);

const columns = ref<TableColumnsType>([
  {
    title: "序号",
    dataIndex: "sequence",
    key: "sequence",
    width: 50,
    customRender: ({index}: { index: number }) => {
      return `${
          (pagination.current - 1) * pagination.pageSize + index + 1
      }`;
    },
    align: "center",
  },
  {
    title: "账号",
    dataIndex: "account",
    resizable: true,
    key: "account",
    width: 100,
    align: "center",
  },
  {
    title: "姓名",
    dataIndex: "name",
    resizable: true,
    key: "name",
    width: 100,
    align: "center",
  },
  {
    title: "手机号",
    dataIndex: "phone",
    resizable: true,
    key: "phone",
    width: 120,
    align: "center",
  },
  {
    title: "邮箱",
    dataIndex: "email",
    resizable: true,
    key: "email",
    width: 130,
    align: "center",
  },
  {
    title: "角色",
    dataIndex: "roles",
    resizable: true,
    key: "roles",
    width: 150,
    align: "center",
  },
  {
    title: "状态",
    dataIndex: "status",
    resizable: true,
    key: "status",
    width: 30,
    align: "center",
  },
  {
    title: "创建时间",
    dataIndex: "createDate",
    resizable: true,
    key: "createDate",
    width: 140,
    align: "center",
  },
  {
    title: "创建人",
    dataIndex: "creator",
    resizable: true,
    key: "creator",
    width: 60,
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "operations",
    resizable: true,
    key: "operations",
    width: 80,
    align: "center",
  },
]);

interface DataItem {
  id: number;
  key: string;
  sequence: string;
  name: string;
  phone: string;
  email: string;
  roles: any[];
  status: number;
  creator: string;
  createDate: string;
}

interface SelectData {
  id: number;
  name: string;
  mark: string;
}

// 下拉框数据源
const selectDataSource = ref([] as SelectData[]);

onMounted(() => {
  // 获取用户列表
  getUserList();
  // 获取角色列表
  getRoleList();
  // 获取权限列表
  getPowerList();
});

const roleColorList = [] as any[];
const colorList = ["pink", "red", "orange", "green", "cyan", "blue", "purple"];
const fnRoleColorHandle = (roleList: any) => {
  const tmpList = roleList.sort(function (a: any, b: any) {
    return a.name - b.name;
  });
  if (tmpList.length > 0) {
    tmpList.map((item: any, index: number) => {
      let tmpObj = {} as any;
      console.log("每次计算的余数", index % 7);
      tmpObj.name = item;
      tmpObj.color = colorList[index % 7];

      roleColorList.push(tmpObj);
    });
  }
  console.log("带颜色的角色列表", roleColorList);
};

const fnRoleHandle = (roleList: any) => {
  roleList.map((item: any) => {
    // debugger;
    if (item.roles?.length > 0) {
      item.roles = item.roles.sort(function (a: any, b: any) {
        return a.value - b.value;
      });
      item.roles.map((role: any) => {
        for (let index = 0; index < roleColorList.length; index++) {
          let roleColor = roleColorList[index];
          if (roleColor.name == role.label) {
            role.color = roleColor.color;
            break;
          }
        }
      });
    }
  });
};
const getRoleList = () => {
  post(`/role/list`, {}, {
    size: 500,
  }).then((res: any) => {
    if (res.errCode == 0) {
      let tmpReslist = res.data.records;
      selectDataSource.value = Object.assign(tmpReslist);
      let tmpList = tmpReslist.map((item: any) => item.name);
      fnRoleColorHandle(tmpList);
    }
  });
};


// 查询相关
const paramData = reactive({
  name: "",
  phone: "",
})
const dataSource = ref([] as DataItem[]);
const getUserList = () => {
  post(`/users/pageList`, paramData, {
    current: pagination.current,
    size: pagination.pageSize,
  }).then((res: any) => {
    if (res.errCode == 0) {
      dataSource.value = Object.assign(res.data.records);
      pagination.total = res.data.total
      fnRoleHandle(dataSource.value);
    }
  });
};

const handleTableChange = () => {
  getUserList();
  // reload();
};


const searchHandleFunc = () => {
  pagination.current = 1;
  getUserList();
};
const data: DataItem[] = [];
const editableData: UnwrapRef<Record<string, DataItem>> = reactive({});

const edit = (key: string) => {
  editableData[key] = cloneDeep(
      dataSource.value.filter((item) => key === item.key)[0]
  );
};
const save = (key: string) => {
  Object.assign(
      dataSource.value.filter((item) => key === item.key)[0],
      editableData[key]
  );
  delete editableData[key];
};

const handleResizeColumn = (w: any, col: any) => {
  col.width = w;
};

// 添加用户相关
// 创建用户表单有关
const addAccountName = ref<string>("");
const addNameValue = ref<string>("");
const addPhoneValue = ref<string>("");
const addRoleValue = ref<string[]>([]);
const addEmailValue = ref<string>("");
const addPasswordValue = ref<string>("");

const modalVisible = ref<boolean>(false);
const addRoleVisible = ref<boolean>(false);

const modalConfirmLoading = ref<boolean>(false);
const addRoleLoading = ref<boolean>(false);
// 添加角色弹窗相关
const addRoleName = ref<string>("");
const addRoleMark = ref<string>("");

const loginName = userStore.info.name;

// 刷新提交的用户角色
function refreshRole(roleList: any) {
  // debugger;
  const selectedRoleList = [] as any[];
  if (roleList.length > 0) {
    roleList.forEach((item: any) => {
      selectDataSource.value.forEach((role: any) => {
        if (role.id == item) {
          let selectedRole = {} as any;
          selectedRole.label = role.name;
          selectedRole.value = role.id;

          selectedRoleList.push(selectedRole);
        }
      });
    });
  }
  return selectedRoleList;
}

const modalHandleOk = () => {
  // 检查是否为空
  if (checkAddRule()) {
    const addRoleList = refreshRole(addRoleValue.value);
    modalConfirmLoading.value = true;
    const addUserParam = {
      creator: loginName,
      name: addNameValue.value,
      account: addAccountName.value,
      phone: addPhoneValue.value,
      roles: addRoleList,
      email: addEmailValue.value,
      loginPwd: addPasswordValue.value
    };
    post(`/users/addOrUpdateUserPO`, addUserParam).then((res: any) => {
      modalConfirmLoading.value = false;
      if (res.errCode == 0) {
        message.success("添加成功");
      } else {
        message.error(res.msg);
      }
      modalVisible.value = false;
      reload();
    });
  }
};

const addHandleFunc = () => {
  modalVisible.value = true;
};

const checkAddRule = () => {
  if (addAccountName.value.trim() == "") {
    message.warning("账号不能为空");
    return false;
  }
  if (addNameValue.value.trim() == "") {
    message.warning("用户名称不能为空");
    return false;
  }
  if (addPhoneValue.value.trim() == "") {
    message.warning("手机号不能为空");
    return false;
  }
  // if (addRoleValue.value.trim() == '') {
  //   message.warning('角色名称不能为空');
  //   return false;
  // }
  if (addPasswordValue.value.trim() == "") {
    message.warning("密码不能为空");
    return false;
  }
  return true;
};

// 删除角色
const deleteRole = (record: any) => {
  const updateStatus = record.status == 0 ? 1 : 0;
  const delRoleParam = {
    id: record.id,
    status: updateStatus,
  };
  post(`/users/disableUser`, delRoleParam).then((res: any) => {
    if (res.errCode == 0) {
      message.success("禁用成功");
    } else {
      message.error(res.msg);
    }
    reload();
  });
};

// 更新用户相关
const updateModalVisible = ref<boolean>(false);
const updateModalConfirmLoading = ref<boolean>(false);
const updateAccountName = ref<string>("");
const updateNameValue = ref<string>("");
const updatePhoneValue = ref<string>("");
const updateRoleValue = ref<string[]>([]);
const updateEmailValue = ref<string>("");
// const updatePasswordValue = ref<string>('');
// 更新用户弹窗相关
const updateRoleName = ref<string>("");
const updateRoleId = ref<number>();

const updateUserInfo = (record: any) => {
  updateRoleName.value = record.name;
  updateRoleId.value = record.id;
  updateAccountName.value = record.account;
  updateNameValue.value = record.name;
  updatePhoneValue.value = record.phone;
  updateRoleValue.value = record.roles?.map((item: any) => {
    return item.value;
  });
  updateEmailValue.value = record.email;

  updateModalVisible.value = true;
};

const checkUpdateRule = () => {
  if (updateRoleName.value.trim() == "") {
    message.warning("角色名称不能为空");
    return false;
  }
  return true;
};

const updateModalHandleOk = () => {
  // 检查是否为空
  if (checkUpdateRule()) {
    // debugger;
    const updateRoleList = refreshRole(updateRoleValue.value);
    updateModalConfirmLoading.value = true;
    const updateRoleParam = {
      id: updateRoleId.value,
      account: updateAccountName.value,
      email: updateEmailValue.value,
      phone: updatePhoneValue.value,
      name: updateNameValue.value,
      roles: updateRoleList,
    };
    post(`/users/addOrUpdateUserPO`, updateRoleParam).then((res: any) => {
      updateModalConfirmLoading.value = false;
      if (res.errCode == 0) {
        message.success("更新成功");
      } else {
        message.error(res.msg);
      }
      updateModalVisible.value = false;
      reload();
    });
  }
};

// 菜单列表

const addRoleHandleOk = () => {
  // 检查是否为空
  if (checkAddRule()) {
    modalConfirmLoading.value = true;
    const selectMenuList = [] as any[];
    console.log("当前选中==========", checkedKeys.value);
    if (checkedKeys.value.length > 0) {
      checkedKeys.value.forEach((selectRole: any) => {
        convertList.forEach((menu: any) => {
          if (menu.id == selectRole) {
            let selectMenu = {label: "", value: Number};
            selectMenu.label = menu.name;
            selectMenu.value = menu.id;
            selectMenuList.push(selectMenu);
          }
        });
      });
    }

    const addRoleParam = {
      name: addRoleName.value,
      mark: addRoleMark.value,
      menuList: selectMenuList,
    };

    console.log("当前提交的采纳数", addRoleParam);
    post(`/role/add`, addRoleParam).then((res: any) => {
      modalConfirmLoading.value = false;
      if (res.errCode == 0) {
        message.success("添加成功");
      } else {
        message.error(res.msg);
      }
      modalVisible.value = false;
      reload();
    });
  }
};

const addRole = () => {
  addRoleVisible.value = true;
};

const addRoleNameInput = (value: string) => {
  addRoleName.value = value;
};

const addRoleMarkInput = (value: string) => {
  addRoleMark.value = value;
};

const addRoleTreeInput = (value: any) => {
  selectRoles.value = value;
};

let convertList = [] as any;

function handlePower(tempPowerList: any[]) {
  tempPowerList.map((topItem: any) => {
    let tempObj = {} as any;
    tempObj.id = topItem.id;
    tempObj.name = topItem.name;
    tempObj.level = topItem.level;
    tempObj.icon = topItem.icon;

    convertList.push(tempObj);

    if (topItem?.children) {
      if (topItem?.children.length > 0) {
        handlePower(topItem?.children);
      }
    }
  });
}

const expandedKeys = ref<string[]>() as any;
const selectedKeys = ref<string[]>() as any;
const checkedKeys = ref<string[]>() as any;
const selectTreeData = ref([] as any);
const handleTreeDataFunc = (treeData: any) => {
  let tempList = [] as any;
  treeData.map((topItem: any) => {
    let tempObj = {} as any;
    tempObj.key = topItem.id;
    tempObj.title = topItem.name;
    tempObj.level = topItem.level < 3 ? "菜单" : "按钮";

    if (topItem?.children) {
      if (topItem?.children.length > 0) {
        tempObj.children = handleTreeDataFunc(topItem?.children);
      }
    }
    tempList.push(tempObj);
  });
  return tempList;
};

const getPowerList = () => {
  post(`/menu/list`).then((res: any) => {
    if (res.errCode == 0) {
      const tempList = res.data;
      selectTreeData.value = handleTreeDataFunc(tempList);
    }
  });
};
</script>
<style lang="less" scoped>


.table-bar {
  padding: 30px 10px 10px 10px;
  width: 100%;
  display: flex;
  justify-content: flex-start;
}

.single-page {
  .main-content {
    width: 100%;
    height: 100%;
  }

  .ant-modal-root {
    :deep(.ant-modal) {
      width: 100px;
      background: red;
    }

    :deep(.ant-modal-body) {
      background: red;
    }
  }

  .main-content {
    width: 100%;
    height: 100%;
  }

  .search-layout {
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .search-label_50 {
      width: 50px;
      text-align: left;
    }

    .search-label_80 {
      width: 85px;
      text-align: left;
    }
  }

  .search-item {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

  .search-content,
  .search-btn {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .input-style {
    display: flex;
    align-items: center;
  }

  .table-style {
    margin-top: 20px;
  }
}

.editable-row-operations a {
  margin-right: 8px;
}

.operations-style {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

// 添加角色
.addRole-contain {
  & > div {
    display: flex;
  }
  width: 440px;

  .addRole-contain_label {
    width: 100px;
  }
}

.adjust-table {
  :deep(.ant-popover-buttons) {
    display: flex;
  }

  :deep(.ant-table-thead) {
    tr {
      th {
        color: #909399 !important;
        font-weight: 500 !important;
        background: #f5f7fa !important;
      }
    }
  }
}
</style>
<style lang="less" scoped>
@import "@/style/page.less";
</style>
